package com.neo.springcloud.lb;


import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class LoadBalancerImpl implements LoadBalancer {

    private AtomicInteger atomic = new AtomicInteger(0);


    public final Integer getAndIncr() {
        int current;
        int next;
        do {
            current = this.atomic.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomic.compareAndSet(current, next));
        log.info(" next index  >>>>>>> {}", next);
        return next;
    }

    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncr() % serviceInstances.size();
        return serviceInstances.get(index);
    }


    public static void main(String[] args) {
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MAX_VALUE + 1);
        System.out.println(Integer.MAX_VALUE + 2);
        System.out.println(Integer.MIN_VALUE - 1);
        System.out.println(Integer.MIN_VALUE - 2);
    }
}
